package com.liang.controller;

import com.liang.pojo.Books;
import com.liang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    //Controller调Service层
    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    //查询全部书籍，并且返回到一个书籍展示页面
    @RequestMapping("/allBooks")
    public String getAllBook(Model model){
        List<Books> list = bookService.queryAllBooks();
        model.addAttribute("list",list);
        return "allBook";
    }

    //跳转到增加书籍页面
    @RequestMapping("/toAddBook")
    public String toAddPaper(){
        return "addBook";
    }

    //增加书籍
    @RequestMapping("/addBook")
    public String addBook(Books books){
        bookService.addBook(books);
        return "redirect:/book/allBooks";
    }

    //跳转到修改书籍页面
    @RequestMapping("/toUpdateBook")
    public String toUpdatePaper(int id,Model model){
        model.addAttribute("book",bookService.queryBookByID(id));
        return "updateBook";
    }

    //修改书籍
    @RequestMapping("/updateBook")
    public String updateBook(Books books){
        bookService.updateBook(books);
        return "redirect:/book/allBooks";
    }

    //删除书籍
    @RequestMapping("/deleteBook/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id){
        bookService.deleteBookByID(id);
        return "redirect:/book/allBooks";
    }

    //通过名字查询书籍
    @RequestMapping("/queryBookName")
    public String queryBookByName(String queryBookName,Model model){
        List<Books> list = bookService.queryBookByName(queryBookName);
        if(list==null || list.size()==0){
            list = bookService.queryAllBooks();
            model.addAttribute("error","未查到");
        }
        model.addAttribute("list",list);
        return "allBook";  //注意：是直接转发，而不是重定向，重定向的话list中查出的是全部books，不是现在add进去的一个books
    }

}
